const Router = require("koa-router");
const { PassThrough } = require("stream");

const queue = Array.from(
  {
    length: 6,
  },
  () => Date.now()
);
const router = new Router();

router.get("/usmile", (ctx, next) => {
  ctx.body = "hello koa router";
});

router.get("/send", (ctx) => {
  const data = ctx.query.salt;
  queue?.push(data ?? Date.now());
  ctx.body = "send is successful";
});

router.get("/keep", (ctx, next) => {
  // 设置响应头
  ctx.set({
    "Cache-Control": "no-cache",
    Connection: "keep-alive",
    "Content-Type": "text/event-stream",
  });

  // 2. 创建流、并作为接口数据进行返回
  const stream = new PassThrough();
  ctx.status = 200;
  ctx.body = stream;

  let timer = setInterval(() => {
    // 模拟数据
    const data = queue.shift();
    if (data !== undefined) {
      // 事件要用两个\n结束
      stream.write(`data: ${data.toString()} \n\n`);
    }
  }, 1000);

  ctx.req.on("close", () => {
    clearInterval(timer);
    console.log("req close");
  });
});

module.exports = router;
